#!/bin/sh
set -eu
umask 077
target=/Library/OFX/Plugins/AELink.ofx.bundle
backup='/Library/Application Support/ResolveAELink/InstallerBackups/d91fc7f2eb8e430eb131a05a3f4b4b25'
bundle_id=dev.ahmdelvn.resolve-ae-link

fail() { echo "AE Link: $*" >&2; exit 1; }
check_host() {
    process_list=$(/bin/ps -axo pid=,command=) || fail "Cannot inspect running applications."
    if printf '%s\n' "$process_list" | /usr/bin/awk '/\/Contents\/MacOS\/Resolve( |$)/ {found=1} END {exit !found}'; then
        fail "Quit Resolve normally after saving your work, then install or roll back again."
    fi
}
check_directories() {
    candidate="$1"
    while [ "$candidate" != / ]; do
        [ ! -L "$candidate" ] || fail "Refusing symlink: $candidate"
        if [ -e "$candidate" ] && [ ! -d "$candidate" ]; then
            fail "Expected a directory: $candidate"
        fi
        candidate=$(/usr/bin/dirname "$candidate")
    done
}
check_owned_bundle() {
    bundle="$1"
    [ -d "$bundle" ] && [ ! -L "$bundle" ] || fail "Not an owned bundle directory: $bundle"
    linked=$(/usr/bin/find "$bundle" -type l -print -quit) || fail "Cannot inspect bundle paths."
    [ -z "$linked" ] || fail "Refusing symlink in bundle: $bundle"
    identifier=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$bundle/Contents/Info.plist") || fail "Cannot read bundle identity."
    [ "$identifier" = "$bundle_id" ] || fail "The target is not the owned AE Link bundle; preserve and inspect it."
    /usr/bin/codesign --verify --deep --strict "$bundle" || fail "Bundle signature verification failed."
}
check_expected_bundle() {
    check_owned_bundle "$target"
    file_list=$(/usr/bin/find "$target" -type f -print) || fail "Cannot inspect consumer files."
    file_count=$(printf '%s\n' "$file_list" | /usr/bin/wc -l)
    [ "$file_count" -eq 3 ] || fail "Installed consumer file inventory mismatch."
    actual=$(/usr/bin/shasum -a 256 "$target"/Contents/Info.plist) || fail "Cannot hash installed consumer."
    [ "${actual%% *}" = 67cfc050669fc599f98daa5c4748d9c3b91e8c2d57b0d53659b176cefa4281cf ] || fail "Installed consumer hash mismatch; preserve and inspect it."
    actual=$(/usr/bin/shasum -a 256 "$target"/Contents/MacOS/AELink.ofx) || fail "Cannot hash installed consumer."
    [ "${actual%% *}" = beeedf2f9db1d169859d2045c3bd8764823b6931877a2fb58bc9223ab5224456 ] || fail "Installed consumer hash mismatch; preserve and inspect it."
    actual=$(/usr/bin/shasum -a 256 "$target"/Contents/_CodeSignature/CodeResources) || fail "Cannot hash installed consumer."
    [ "${actual%% *}" = 6686de10a28a2fe11b36cbb86dcbacc827cfc4ea116b4dabf1845e5aee629e9b ] || fail "Installed consumer hash mismatch; preserve and inspect it."
}

check_host
check_directories "$target"
check_directories "$backup"
[ -f "$backup/previous-state" ] && [ ! -L "$backup/previous-state" ] || fail "Missing installer backup record."
check_expected_bundle
printf 'verified\n' > "$backup/installed"
